<template>
	<a-select
		v-model:value="henhouseId"
		style="width: 100%"
		allow-clear
		placeholder="选择鸡舍"
		:options="options"
		@change="handleChange"
	></a-select>
</template>

<script setup="henhouseSelect">
	import bizHenhouseApi from '@/api/henhouse/bizHenhouseApi';
	const emit = defineEmits(['update:henhouseId', 'update:henhouseName']);
	const henhouseId = ref();
	const options = ref([]);
	const listData = ref([])


	// 获取鸡舍列表
	const getBarnList = () => {
		bizHenhouseApi.getBizHenhouseList()
			.then(resp =>{
				listData.value = resp;
				mapDataToOptions();
			})
			.catch(resp =>{
				console.log("catch:",resp);
			});
	}

	const mapDataToOptions = () => {
		options.value = listData.value.map(item => ({
			value: item.id,
			label: item.name,
		}));
	};

	onMounted(() =>{
		getBarnList();
	});

	const handleChange = (value) =>{
		if(value === undefined){
			emit('update:henhouseId', undefined);
			emit('update:henhouseName', undefined);
		}
		const selectedHenhouseId = value; // 获取选择的鸡舍id
		const selectedHenhouse = listData.value.find(henhouse => henhouse.id === selectedHenhouseId); // 通过id在listData数组中查找对应的鸡舍对象
		const selectedHenhouseName = selectedHenhouse ? selectedHenhouse.name : ''; // 获取对应的鸡舍名称
		// 触发自定义事件
		if (selectedHenhouseId) {
			emit('update:henhouseId', selectedHenhouseId);
		}
		if (selectedHenhouseName) {
			emit('update:henhouseName', selectedHenhouseName);
		}
	}

	const clearHenhouseId = () => {
		henhouseId.value = undefined;
		emit('update:henhouseId', undefined);
	}

	const initHenhouseId = (id) =>{
		henhouseId.value = id;
		emit('update:henhouseId', id);
	}

	defineExpose({
		clearHenhouseId,
		initHenhouseId,
	});

</script>

<style scoped>

</style>
